package com.tencent.sr.iris.activity.common.util;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tencent.sr.rmall.springbootstarter.monitor.util.MonitorUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SentinelUtil {

    /**
     * 检查是否限流
     *
     * @param path
     * @return
     */
    public static void checkSentinelLimit(String path) throws BlockException {
        long startTime = System.currentTimeMillis();
        Entry entry = null;
        Throwable throwable = null;
        try {
            // 资源名可使用任意有业务语义的字符串，注意数目不能太多（超过 1K），超出几千请作为参数传入而不要直接作为资源名
            entry = SphU.entry(path);
        } catch (BlockException ex) {
            throwable = ex;
            log.error("checkSentinelLimit {} 触发限流", path);
            throw ex;
        } catch (Exception e) {
            throwable = e;
            log.error("checkSentinelLimit error, {}", path, e);
            // 若需要配置降级规则，需要通过这种方式记录业务异常
            Tracer.traceEntry(e, entry);
            throw e;
        } finally {
            // 务必保证 exit，务必保证每个 entry 与 exit 配对
            if (entry != null) {
                entry.exit();
            }
            MonitorUtil.getSingleMonitorService().logTransaction("checkSentinelLimit", path,
                    startTime, throwable);
        }
    }
}
